import React, { useEffect, useMemo, useState } from 'react';
import type { CSSProperties, FC } from 'react';
import type { DragSourceMonitor } from 'react-dnd';
import { useDrag } from 'react-dnd';
import { useDispatch } from 'react-redux';
import { RootDispatch } from '@/store';
import { getEmptyImage } from 'react-dnd-html5-backend';

const style: CSSProperties = {
  border: '1px dashed gray',
  padding: '0.5rem',
  margin: '0.5rem',
};

export const SourceBox: FC<any> = (props) => {
  const { printReport } = useDispatch<RootDispatch>();

  const [{ isDragging }, drag, dragPreview] = useDrag(
    () => ({
      type: props.type || '',
      canDrag: true,
      // 传递参数
      item: {
        kk: '参数',
        ...props,
      },
      collect: (monitor: DragSourceMonitor) => {
        return {
          isDragging: monitor.isDragging(),
        };
      },
      end(draggedItem, monitor) {
        console.log('send', props);
        printReport.updateState({
          selectedStatus: 'mouseUp',
          // selectData: {},
        });
      },
    }),
    [],
  );

  useEffect(() => {
    dragPreview(getEmptyImage(), { captureDraggingState: true });
  }, []);

  const containerStyle = useMemo(
    () => ({
      ...style,
      opacity: isDragging ? 0.4 : 1,
      cursor: 'move',
    }),
    [isDragging],
  );

  return (
    <div style={{ width: 300 }}>
      <div
        ref={drag}
        style={{ ...containerStyle }}
        onMouseDown={() => {
          printReport.updateState({
            selectedStatus: 'mouseDown',
            selectData: props,
          });
        }}
      >
        <span>{props.title}</span>
      </div>
    </div>
  );
};

export default SourceBox;
